﻿using System;
using System.Net;
using System.Xml;
using System.Collections;
namespace FindDomains
{
    // Bing API 2.0 code sample demonstrating the use of the
    // Web SourceType over the XML Protocol.
    static class WebSample
    {
        // Replace the following string with the AppId you received from the
        // Bing Developer Center.
        public static string AppId = "";
        public static int timeout = 5000;

        public static HttpWebRequest BuildRequest(string query, string offset)
        {
            string requestString = "http://api.bing.net/xml.aspx?"

                // Common request fields (required)
                + "AppId=" + AppId
                + "&Query=ip:" + query
                + "&Sources=Web"

                // Common request fields (optional)
                + "&Version=2.0"
                + "&Market=en-us"
                + "&Adult=Moderate"
                + "&Options=EnableHighlighting"

                // Web-specific request fields (optional)
                + "&Web.Count=50"
                + "&Web.Offset=" + offset
                + "&Web.Options=DisableQueryAlterations";

            // Create and initialize the request.
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(
                requestString);
            request.Timeout = timeout;
            return request;
        }

        public static UniqueArrayList DisplayResponse(HttpWebResponse response)
        {
            // Load the response into an XmlDocument.
            XmlDocument document = new XmlDocument();
            document.Load(response.GetResponseStream());

            // Add the default namespace to the namespace manager.
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(
                document.NameTable);
            nsmgr.AddNamespace(
                "api",
                "http://schemas.microsoft.com/LiveSearch/2008/04/XML/element");

            XmlNodeList errors = document.DocumentElement.SelectNodes(
                "./api:Errors/api:Error",
                nsmgr);

            if (errors.Count > 0)
            {
                // There are errors in the response. Display error details.
                DisplayErrors(errors);
            }
            else
            {
                // There were no errors in the response. Display the
                // Web results.
                return DisplayResults(document.DocumentElement, nsmgr);
            }
            return new UniqueArrayList();
        }

        public static UniqueArrayList DisplayResults(XmlNode root, XmlNamespaceManager nsmgr)
        {
            UniqueArrayList arrayList = new UniqueArrayList();
            // Add the Web SourceType namespace to the namespace manager.
            nsmgr.AddNamespace(
                "web",
                "http://schemas.microsoft.com/LiveSearch/2008/04/XML/web");

            XmlNode web = root.SelectSingleNode("./web:Web", nsmgr);
            XmlNodeList results = web.SelectNodes(
                "./web:Results/web:WebResult",
                nsmgr);

            string version = root.SelectSingleNode("./@Version", nsmgr).InnerText;
            string searchTerms = root.SelectSingleNode(
                "./api:Query/api:SearchTerms",
                nsmgr).InnerText;
            int offset;
            int.TryParse(
                web.SelectSingleNode("./web:Offset", nsmgr).InnerText,
                out offset);
            int total;
            int.TryParse(
                web.SelectSingleNode("./web:Total", nsmgr).InnerText,
                out total);

            //// Display the results header.
            //Console.WriteLine("Bing API Version " + version);
            //Console.WriteLine("Web results for " + searchTerms);
            //Console.WriteLine(
            //    "Displaying {0} to {1} of {2} results",
            //    offset + 1,
            //    offset + results.Count,
            //    total);
            //Console.WriteLine();

            // Display the Web results.
            System.Text.StringBuilder builder = new System.Text.StringBuilder();

            foreach (XmlNode result in results)
            {
                string fullURL = result.SelectSingleNode("./web:Url", nsmgr).InnerText;
                fullURL = fullURL.Substring(0,fullURL.IndexOf("/",9));
                arrayList.add(fullURL);
            }
            return arrayList;
        }

        public static void DisplayErrors(XmlNodeList errors)
        {
            // Iterate over the list of errors and display error details.
            Console.WriteLine("Errors:");
            Console.WriteLine();
            foreach (XmlNode error in errors)
            {
                foreach (XmlNode detail in error.ChildNodes)
                {
                    Console.WriteLine(detail.Name + ": " + detail.InnerText);
                }

                Console.WriteLine();
            }
        }

        public static int GetNumber(string query)
        {
            HttpWebRequest httpWebRequest = BuildRequest(query,"0");
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            XmlDocument document = new XmlDocument();
            document.Load(httpWebResponse.GetResponseStream());

            // Add the default namespace to the namespace manager.
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(
                document.NameTable);
            // Add the Web SourceType namespace to the namespace manager.
            nsmgr.AddNamespace(
                "web",
                "http://schemas.microsoft.com/LiveSearch/2008/04/XML/web");

            nsmgr.AddNamespace(
    "api",
    "http://schemas.microsoft.com/LiveSearch/2008/04/XML/element");

            XmlNode web = document.DocumentElement.SelectSingleNode("./web:Web", nsmgr);
              XmlNodeList errors = document.DocumentElement.SelectNodes(
                "./api:Errors/api:Error",
                nsmgr);

              if (errors.Count > 0)
              {
                  // There are errors in the response. Display error details.
                  DisplayErrors(errors);
              }
              else
              {
                  int total;
                  int.TryParse(
                      web.SelectSingleNode("./web:Total", nsmgr).InnerText,
                      out total);

                  return total;
              }
              return -1;
        }
    }
}
